package com.chaochis.springboottestdemo.config.reqResConfig.dispatcherConfig;

import com.chaochis.springboottestdemo.config.corsConfig.CorsProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
@Component
public class MyDispatcher {

  @Qualifier("corsProperties")
  private final CorsProperties corsProperties;

  public MyDispatcher(CorsProperties corsProperties) {
    this.corsProperties = corsProperties;
  }

  @Bean
  @Qualifier(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
  public DispatcherServlet dispatcherServlet() {
    return new DispatcherServlet(){
      @Override
      protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        super.doDispatch(new CustomRequestWrapper(request, corsProperties), new CustomResponseWrapper(response));
      }
    };
  }
}

